<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of wxmenu
 * 微信自定义菜单管理
 * @author xlp
 */
class menuApi {

    protected static $appId = null;  //企业CorpID，可在企业号后台设置中查看
    protected static $corpSecret = null;  //企业corpSecret，可在企业号后台设置->权限管理对应的管理组中查看
    protected static $menuData = null;
    protected static $city_id = 0;
    protected static $agentId = null; //应用ID，可在企业号后台应用中心对应的应用中查看
    static $token = null;
    static $errCode = 0;
    static $errorMsg = null;
    static $accessTokenPre = 'token/weixin/qy/access_token_';

    //请求api前缀

    static function init($city_id) {
        $setting = F('steward/setting_city_' . $city_id);
        if (!isset($setting['corp_info'])) {
            showError('缓存有误，请刷新');
        }
        $setting = $setting['corp_info'];
        if (isHave($setting['corpSecret']) && isHave($setting['corpID'])) {
            self::$city_id = $city_id;
            self::$appId = $setting['corpID'];
            self::$corpSecret = $setting['corpSecret'];
            self::$agentId = $setting['agentId'];
        } else {
            showError('api Error:请设置CorpId、CorpSecret');
        }
    }

    static function getErrorMsg() {
        return self::$errorMsg;
    }

    /**
     * 删除验证数据
     * @param string $appid
     */
    static public function resetAuth() {
        self::$token = '';
        S(self::$accessTokenPre . self::$appId, null);
        self::gettoken();
        return true;
    }

    /*
     * 检查是否需要重新获取accesstoken
     * 并记下日志
     */

    static public function checkAccessToken() {
        if (self::$errCode == 40001) {
            self::resetAuth();
            saveLog('qy/accessToken/reset', 'weixin.menu');
            return true;
        }
        return false;
    }

    static function gettoken() {
        if (self::$token) {
            return self::$token;
        }

        self::$token = S(self::$accessTokenPre . self::$appId);
        if (!self::$token) {
            $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . self::$appId . '&corpsecret=' . self::$corpSecret);
            $result = json_decode($result, true);
            if ($result && !isset($result['errcode'])) {
                S(self::$accessTokenPre . self::$appId, $result['access_token'], $result['expires_in']);
                self::$token = $result['access_token'];
            } else {
                S(self::$accessTokenPre . self::$appId, $result['access_token'], $result['expires_in']);
                self::$errCode = $result['errcode'];
                self::$errorMsg = $result['errcode'];
                self::checkAccessToken();
                return false;
            }
        }
        return self::$token;
    }

    static function setmenu() {
        self::gettoken();
        $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/menu/create?access_token=' . self::$token . '&agentid=' . self::$agentId, self::$menuData);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return true;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    static function getmenu() {
        self::gettoken();
        $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/menu/get?access_token=' . self::$token . '&agentid=' . self::$agentId);
        $result = json_decode($result, true);
        if ($result && !isset($result['errcode'])) {
            return $result;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    static function delmenu() {
        self::gettoken();
        $result = getHttp('https://qyapi.weixin.qq.com/cgi-bin/menu/delete?access_token=' . self::$token . '&agentid=' . self::$agentId);
        $result = json_decode($result, true);
        if ($result && !$result['errcode']) {
            return true;
        } else {
            self::$errorMsg = $result['errcode'] . '-' . $result['errmsg'];
            return false;
        }
    }

    /*     * ************************************************************ 
     * 
     *  使用特定function对数组中所有元素做处理 
     *  @param  string  &$array     要处理的字符串 
     *  @param  string  $function   要执行的函数 
     *  @return boolean $apply_to_keys_also     是否也应用到key上 
     *  @access public 
     * 
     * *********************************************************** */

    static function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
        static $recursive_counter = 0;
        if (++$recursive_counter > 1000) {
            die('possible deep recursion attack');
        }
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                self::arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }

            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
        $recursive_counter--;
    }

    static function setMenuData($menuData) {
        self::arrayRecursive($menuData, 'urlencode', true);
        $json = json_encode($menuData);
        self::$menuData = '{"button":' . urldecode($json) . "}";
        return self::$menuData;
    }

}
